#include "generatorobject.h"
#include "../../ImageAcquisitor/global.h"

#include <QSettings>
#include <QCoreApplication>

GeneratorObject::GeneratorObject(QObject *parent) :
    serialPort(new QSerialPort(this)),
    QObject(parent)
{
    connect(serialPort, SIGNAL(readyRead()), this, SLOT(onSerialPortReadReady()));
}

void GeneratorObject::onOpenSerialPort()
{
    QSettings s(QCoreApplication::applicationDirPath() + "/"PLUGIN_GENERATOR_CONFIG, QSettings::IniFormat);
    s.setIniCodec(QSETTINGS_CODEC_NAME);
    name = s.value(GENERATOR_GENERAL_NAME).toString();
    portName = s.value(GENERATOR_SERIALPORT_NAME).toString();
    serialPort->setPortName(portName);
    if (!serialPort->open(QIODevice::ReadWrite)) {
        emit deviceStatus(GenSerialPortOpenFailed, serialPort->errorString());
    } else {
        int baud = s.value(GENERATOR_SERIALPORT_BAUDRATE).toInt();
        int dbits = s.value(GENERATOR_SERIALPORT_DATABITS).toInt();
        int parity = s.value(GENERATOR_SERIALPORT_PARITY).toInt();
        int sbits = s.value(GENERATOR_SERIALPORT_STOPBITS).toInt();
        serialPort->setBaudRate((QSerialPort::BaudRate)baud);
        serialPort->setDataBits((QSerialPort::DataBits)dbits);
        serialPort->setParity((QSerialPort::Parity)parity);
        serialPort->setStopBits((QSerialPort::StopBits)sbits);
        emit deviceStatus(GenSerialPortOpened);
    }

    int cnt = s.value(GENERATOR_ERRORCODE_LASTCOUNT).toInt();
    for (int i = 0; i <= cnt; ++i) {
        QString str = s.value(GENERATOR_ERRORCODE_KEY + QString::number(i)).toString();
        errHash.insert(i, str);
    }
}
